#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/timeb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>

#include "alarm_info.h"
#include "cgi_common.h"

char g_alarm_info_buf[ALARM_INFO_LINE_NUMBER][ALARM_INFO_COL_NUMBER];

//alarm info
static char* level_debug_str = "[Debug]";
static char* level_info_str = "[ Info]";
static char* level_warning_str = "[ Warn]";
static char* level_error_str = "[Error]";

void set_alarm_info_buf(char *alarm_info, ...)
{
	static int index = 0;
	int i = 0;
	if (alarm_info != NULL)
	{
		if (memcmp(alarm_info, "clear", 5) == 0)//clear
		{
			for (i = 0; i < index; i++)
			{
				memset(g_alarm_info_buf[i], '\0', ALARM_INFO_COL_NUMBER);
			}
			index = 0;
		}
		else
		{
			//add header
			char * level_str = NULL;
			level_str = level_info_str;
			char printf_buf[ALARM_INFO_COL_NUMBER] = { '\0' };
			memset(printf_buf, '\0', ALARM_INFO_COL_NUMBER);
			struct timeval tv;
			gettimeofday(&tv, NULL);
			long long sec = tv.tv_sec;
			long long msec = tv.tv_usec / 1000;
			long long minute = (sec % (3600LL)) / (60LL);
			long long hour = (sec % (86400LL)) / (3600LL);
			sec = sec % 60LL;
			/*sprintf(printf_buf, "%s_%02lld:%02lld:%02lld:%03lld: ", level_str, hour, minute, sec, msec);*/

			struct tm now_time;
			localtime_r(&tv.tv_sec, &now_time);
			sprintf(printf_buf, "%s_%04d/%02d/%02d_%02d:%02d:%02d:%03lld: ",
				level_str, now_time.tm_year + 1900, now_time.tm_mon + 1, now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec, msec);

			//analyse the data
			va_list  arg;
			int done = 0;
			int in_buff_len = strlen(printf_buf);
			va_start(arg, alarm_info);
			done = vsnprintf(printf_buf + in_buff_len, sizeof(printf_buf) - 1 - in_buff_len, alarm_info, arg);
			va_end(arg);

			//end
			if ((index != 0) && (index % ALARM_INFO_LINE_NUMBER == 0))//move
			{
				memmove(g_alarm_info_buf[0], g_alarm_info_buf[1], (ALARM_INFO_LINE_NUMBER - 1) * ALARM_INFO_COL_NUMBER * sizeof(char));
				memset(g_alarm_info_buf[index - 1], '\0', ALARM_INFO_COL_NUMBER);
				memcpy(g_alarm_info_buf[index - 1], printf_buf, strlen(printf_buf));
				index--;
			}
			else
			{
				memset(g_alarm_info_buf[index], '\0', ALARM_INFO_COL_NUMBER);
				memcpy(g_alarm_info_buf[index], printf_buf, strlen(printf_buf));
			}
			index++;
		}
	}
}

int get_alarm_info_buf(int index_alarm, char *alarm_info)
{
	int ret_len = 0;
	if (index_alarm < ALARM_INFO_LINE_NUMBER)
	{
		ret_len = strlen(g_alarm_info_buf[index_alarm]);
	}
	if (alarm_info != NULL)
	{
		if (ret_len == 0)
		{
			memset(alarm_info, '\0', ALARM_INFO_COL_NUMBER);
		}
		else
		{
			memcpy(alarm_info, g_alarm_info_buf[index_alarm], ret_len);
		}
	}
	return ret_len;
}